package cloud.tianai.mate.captcha.interceptor.impl;

import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.generator.AbstractImageCaptchaGenerator;
import cloud.tianai.captcha.generator.common.model.dto.CaptchaExchange;
import cloud.tianai.captcha.generator.common.model.dto.GenerateParam;
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
import cloud.tianai.captcha.interceptor.Context;
import cloud.tianai.mate.captcha.common.constant.MateCaptchaTypeConstant;
import cloud.tianai.mate.captcha.generator.common.util.ImageShuffleUtils;
import lombok.Data;

import java.util.List;

/**
 * @Author: 天爱有情
 * @date 2023/4/24 16:51
 * @Description 将图片打乱，在前端使用canvas进行重组
 */
public class ShuffleImageProcessor implements CaptchaInterceptor {
    /** 打乱背景图的key. */
    public static final String SHUFFLE_IMAGE_KEY = "shuffleImage";


    @Override
    public String getName() {
        return "shuffle_image_processor";
    }

    @Override
    public void beforeWrapImageCaptchaInfo(Context context,
                                           CaptchaExchange captchaExchange,
                                           AbstractImageCaptchaGenerator abstractImageCaptchaGenerator) {
        GenerateParam param = captchaExchange.getParam();
        if (captchaExchange.getBackgroundImage() == null
                || !Boolean.TRUE.equals(param.getParam(SHUFFLE_IMAGE_KEY))
                || CaptchaTypeConstant.CONCAT.equals(param.getType())
        ) {
            return;
        }
        int x = 5;
        int y = 2;
        if (MateCaptchaTypeConstant.ROTATE_DEGREE.equals(param.getType())) {
            y = 4;
            x = 4;
        }
        // 只打乱背景图片
        ImageShuffleUtils.ShuffleImageResponse shuffle = ImageShuffleUtils.shuffle(captchaExchange.getBackgroundImage(), x, y);
        captchaExchange.setBackgroundImage(shuffle.getImage());
        ShuffleViewData viewData = new ShuffleViewData();
        viewData.setX(x);
        viewData.setY(y);
        viewData.setPos(shuffle.getPos());
        captchaExchange.getCustomData().putViewData("shuffle", viewData);
    }

    @Data
    public static class ShuffleViewData {
        private Integer x;
        private Integer y;
        private List<Integer> pos;
    }
}
